﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using Churchtoolkit.DataAccess.Entities;
using Churchtoolkit.DataAccess.Repositories;
using Churchtoolkit.Utils.Authentication;

namespace Churchtoolkit.Web.Shell.Services
{
    public class AuthenticationService : IAuthentication
    {
        #region [ Fields ]
        private readonly SecureMemberDtoRepository _secureMemberDtoRepository; 
        #endregion

        #region [ Constructor ]
        public AuthenticationService(SecureMemberDtoRepository secureMemberDtoRepository)
        {
            _secureMemberDtoRepository = secureMemberDtoRepository;
        }
        #endregion

        #region IAuthentication Members

        public ICurrentMember CurrentLogedInMember 
        {
            get
            {
                return (CurrentMember) CurrentLogedInMemberDto;
            }
        }
        
        #endregion

        #region [helper]
        public SecureMemberDto CurrentLogedInMemberDto
        {
            get
            {
                if (HttpContext.Current != null)
                {
                    var secureMemberDto = HttpContext.Current.Items["CurrentLogedInMember"] as SecureMemberDto;
                    if (secureMemberDto == null)
                    {
                        secureMemberDto =
                            _secureMemberDtoRepository.Find(m => m.Email = HttpContext.Current.User.Identity.Name).Single();
                        HttpContext.Current.Items["CurrentLogedInMember"] = secureMemberDto;
                    }
                    return secureMemberDto;
                }
                return null;
            }
        }
        #endregion
    }
}
